package com.shwread.android.qysw.activity;

import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.shwread.android.qysw10000136.R;
import com.shwread.android.ui.dialog.NetworkDialog;
import com.shwread.android.ui.widget.BookMarkDialog;
import com.shwread.android.ui.widget.BookMarkDialog.OnBookMarkMenuClickListener;
import com.shwread.httpsdk.util.NetUtil;

import org.geometerplus.android.fbreader.libraryService.BookCollectionShadow;
import org.geometerplus.android.util.QyreaderPerferencesUtil;
import org.geometerplus.fbreader.book.Book;
import org.geometerplus.fbreader.book.Bookmark;
import org.geometerplus.fbreader.book.Bookmark.DateType;
import org.geometerplus.fbreader.fbreader.ActionCode;
import org.geometerplus.fbreader.fbreader.FBReaderApp;
import org.geometerplus.zlibrary.ui.android.library.ZLAndroidLibrary;
import org.xml.sax.SAXException;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import logic.bean.TOCItem;
import logic.beanenum.BookStatus_Enum;
import logic.constants.Const;
import logic.constants.DefaultConsts;
import logic.dao.BookDao;
import logic.dao.BookMarksDao;
import logic.dao.UserDao;
import logic.util.FileUtil;
import logic.util.SDcardUtil;
import logic.util.Util;
import logic.util.logutil.LogUtil;
import logic.util.qryChapterInfoUtil;
import logic.xml.parser.NCXHandler;


/**
 * @Project： Lqyd_Android0907
 * @Title：AnnotationsActivity
 * @Description：目录、笔记、书签
 * @Author：wayne
 * @Date：2014年9月9日下午2:54:02
 */
public class AnnotationsActivity
        extends
        BaseBusinessActivity
        implements
        OnClickListener,
        OnCheckedChangeListener,
        OnBookMarkMenuClickListener
{
	private final static int UPDATEUI_GETBOOKNOTE = 118;
	private RelativeLayout   chapterLayout;
	private RelativeLayout   bookmarkLayout;
	private RelativeLayout   bookmarkEmptyLayout;
	private RelativeLayout   commentsLayout;
	private RelativeLayout   commentsEmptyLayout;
	private ImageView        booknoteLine;
	private View             bookChapterEmptyLayout;
	private ListView         listViewChapter;
	private ListView         listViewBookMark;
	private ListView         listViewBookNote;
	private RadioGroup       radioGroup;
	private ChapterAdapter   adapter;
	private BookMarkAdapter  bookMarkAdapter;
	private BookNotesAdapter bookNotesAdapter;
	private ImageView           backButton;
	private TextView         tvBookName;
	
	private String           bookId;
	private String           bookName;
	private int              bookstatus           = 2;
	
	private int chapterCurrent = -1;
	
	private List<TOCItem>    catalogList;
	
	private Context          context;
	
	private String           clickChapterId       = "";
	private String           chapterName          = "";
	
	public FBReaderApp       myFBReaderApp;
	
	public static Book       myBook;
	private List<Bookmark>   bookmarks            = new ArrayList<Bookmark>(); //书签
	private List<Bookmark>   bookNotes            = new ArrayList<Bookmark>(); //笔记和批注
	private BookMarkDialog   bookMarkDialog;
	BookMarksDao             bmDao;
	private boolean          isRefreshBookReader  = false;
	
	private String           account              = "";
	
	private Handler          handler              = new Handler()
	                                              {
		                                              
		                                              @Override
		                                              public void handleMessage(Message msg) {
			                                              switch (msg.what) {
															  case 100:
																  initDirctory();
																  adapter.notifyDataSetChanged();
																  break;
															  case UPDATEUI_GETBOOKNOTE:
																  listViewBookMark.setAdapter(bookMarkAdapter);
																  listViewBookNote.setAdapter(bookNotesAdapter);
																  //bookNotesAdapter.notifyDataSetChanged();
																  break;
															  default:
																  break;
														  }
													  }
													  
	                                              };
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.annotations_tabmain);
		context = this;
		
		account = UserDao.getInstance(this).getLastLoginUser().getAccount();
		Bundle bundle = getIntent().getExtras();
		if (null != bundle)
		{
			bookId = bundle.getString(DefaultConsts.book_contentId_s);
			bookstatus = bundle.getInt(ReadingBookActivity.BOOKSTATUS);
			bookName = bundle.getString(DefaultConsts.book_name);
			chapterCurrent = bundle.getInt(DefaultConsts.chapterId_current_i);
		}
		
		myFBReaderApp = (FBReaderApp) FBReaderApp.Instance();
		if (myFBReaderApp == null)
		{
			myFBReaderApp = new FBReaderApp(new BookCollectionShadow());
		}
		bmDao = BookMarksDao.getInstance(this);
		adapter = new ChapterAdapter();
		bookMarkAdapter = new BookMarkAdapter();
		bookNotesAdapter = new BookNotesAdapter();
		
		bookMarkDialog = new BookMarkDialog(this, this);
		
		ReadingBookActivity readingActivity = (ReadingBookActivity) ((ZLAndroidLibrary) ZLAndroidLibrary.Instance()).getActivity();
		catalogList = readingActivity.getCatalogList();
		findViews();
		
		new Thread()
		{
			public void run() {
				//				initBookMark();
				getBookNotes();
			};
		}.start();
	}
	
	void getBookNotes() {
		if (bookId == null) { return; }
		String bookDb_id = BookDao.getInstance(this).getDbIdByContentId(bookId, account);
		List<Bookmark> thisBookBookmarks = bmDao.loadOneBookNotes(bookDb_id, bookId, "");
		
		for (Bookmark bookmark : thisBookBookmarks)
		{
			if (bookmark.getMyTypeID() == 1)
			{
				bookmarks.add(bookmark);
			}
			else
			{
				bookNotes.add(bookmark);
			}
		}
		getUIHandler().sendEmptyMessage(UPDATEUI_GETBOOKNOTE);
	}
	
	@Override
	protected void onPause() {
		super.onPause();
	}
	
	private void findViews() {
		chapterLayout = (RelativeLayout) findViewById(R.id.chapter_layout);
		bookmarkLayout = (RelativeLayout) findViewById(R.id.bookmark_layout);
		commentsLayout = (RelativeLayout) findViewById(R.id.remark_layout);
		bookmarkEmptyLayout = (RelativeLayout) findViewById(R.id.bookmark_list_empty);
		commentsEmptyLayout = (RelativeLayout) findViewById(R.id.remark_list_empty);
		booknoteLine = (ImageView) findViewById(R.id.note_noteinfo_vertical_line);
		bookChapterEmptyLayout = (View) findViewById(R.id.catalog_list_empty);
		backButton = (ImageView) findViewById(R.id.read_directory_page_turning_btn);
		booknoteLine.setVisibility(View.VISIBLE);
		
		listViewChapter = (ListView) findViewById(R.id.chapter_list);
		listViewBookMark = (ListView) findViewById(R.id.bookmark_list);
		listViewBookNote = (ListView) findViewById(R.id.remark_list);
		radioGroup = (RadioGroup) findViewById(R.id.button_layout);
		tvBookName = (TextView) findViewById(R.id.annotations_book_name_tv);
		
		listViewChapter.setAdapter(adapter);
		listViewChapter.setSelection(chapterCurrent);
		adapter.notifyDataSetInvalidated();
		
		radioGroup.setOnCheckedChangeListener(this);
		backButton.setOnClickListener(this);
		listViewChapter.setOnItemClickListener(new ListViewItemClick());
		listViewBookMark.setOnItemClickListener(bookMarkClickListener);
		listViewBookMark.setOnItemLongClickListener(bookMarkLongClickLsitener);
		listViewBookNote.setOnItemClickListener(bookNoteClickListener);
		listViewBookNote.setOnItemLongClickListener(bookNoteLongClickLsitener);
		tvBookName.setText(bookName);
		
		if (catalogList == null) bookChapterEmptyLayout.setVisibility(View.VISIBLE);
	}
	
	private void initDirctory() {
		String dirctory = "";
		if (bookstatus == BookStatus_Enum.DOWNLOAD.getValue()) dirctory = FileUtil.DownloadPath() + bookId + "/META-INF/book.ncx";
		else dirctory = FileUtil.OnlinePath(bookId) + FileUtil.Book_CATALOGUE;
		SAXParserFactory factory = SAXParserFactory.newInstance();
		SAXParser parser;
		try
		{
			parser = factory.newSAXParser();
			InputStream is = new FileInputStream(new File(dirctory));
			NCXHandler handle = new NCXHandler();
			parser.parse(is, handle);
			is.close();
			catalogList = handle.getNavPointList();
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
		catch (ParserConfigurationException e)
		{
			e.printStackTrace();
		}
		catch (SAXException e)
		{
			e.printStackTrace();
		}
		
	}
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.read_directory_page_turning_btn:
				onBackPressed();
				break;
			
			default:
				break;
		}
	}
	
	@Override
	public void onBackPressed() {
		if (isRefreshBookReader)
		{
			setResult(RESULT_OK);
		}
		super.onBackPressed();
	}
	
	@Override
	public Handler getUIHandler() {
		return handler;
	}
	
	@Override
	public void onCheckedChanged(RadioGroup arg0, int arg1) {
		chapterLayout.setVisibility(View.GONE);
		bookmarkLayout.setVisibility(View.GONE);
		commentsLayout.setVisibility(View.GONE);
		bookChapterEmptyLayout.setVisibility(View.GONE);
		switch (arg1) {
			case R.id.chapter_tab:
				chapterLayout.setVisibility(View.VISIBLE);
				if (adapter.getCount() <= 0)
				{
					bookChapterEmptyLayout.setVisibility(View.VISIBLE);
				}
				
				break;
			case R.id.bookmark_tab:
				bookmarkLayout.setVisibility(View.VISIBLE);
				if (bookMarkAdapter.getCount() <= 0)
				{
					bookmarkEmptyLayout.setVisibility(View.VISIBLE);
				}
				break;
			case R.id.remark_tab:
				commentsLayout.setVisibility(View.VISIBLE);
				if (bookNotesAdapter.getCount() <= 0)
				{
					booknoteLine.setVisibility(View.GONE);
					commentsEmptyLayout.setVisibility(View.VISIBLE);
				}
				break;
			default:
				break;
		}
	}
	
	private class ChapterAdapter
	        extends
	        BaseAdapter
	{
		
		@Override
		public int getCount() {
			if (null == catalogList) return 0;
			return catalogList.size();
		}
		
		@Override
		public Object getItem(int position) {
			return catalogList.get(position);
		}
		
		@Override
		public long getItemId(int position) {
			return position;
		}
		
		@Override
		public View getView(final int position, View convertView, ViewGroup parent) {
			if (convertView == null)
			{
				convertView = getLayoutInflater().inflate(R.layout.catalog_list_item, null);
			}
			TextView chapterName = (TextView) convertView.findViewById(R.id.catalog_listview_item_tv);
			
			TOCItem item = (TOCItem) getItem(position);
			chapterName.setText(item.getNavLabel());
			if(position==chapterCurrent)
			{
				chapterName.setTextColor(Color.parseColor("#f3a723"));
			}
			else
			{
				chapterName.setTextColor(Color.parseColor("#333333"));
			}
			
			return convertView;
		}
		
	}
	
	@Override
	public void deleteBookMark(Bookmark bookmark) {
		bmDao.deleteBookmark(bookmark);
		bookmarks.remove(bookmark);
		((BaseAdapter) listViewBookMark.getAdapter()).notifyDataSetChanged();
		showBookMarkEmptyView();
		
	}
	
	@Override
	public void deleteBookNote(Bookmark bookmark) {
		bmDao.deleteBookmark(bookmark);
		myFBReaderApp.deleteRemarkIcon(bookmark);
		bookNotes.remove(bookmark);
		((BaseAdapter) listViewBookNote.getAdapter()).notifyDataSetChanged();
		isRefreshBookReader = true;
		showBookNoteEmptyView();
	}
	
	void showBookMarkEmptyView() {
		if (bookMarkAdapter.getCount() <= 0)
		{
			bookmarkEmptyLayout.setVisibility(View.VISIBLE);
		}
	}
	
	void showBookNoteEmptyView() {
		if (bookNotesAdapter.getCount() <= 0)
		{
			booknoteLine.setVisibility(View.GONE);
			commentsEmptyLayout.setVisibility(View.VISIBLE);
		}
	}
	
	private OnItemClickListener     bookMarkClickListener     = new OnItemClickListener()
	                                                          {
		                                                          @Override
		                                                          public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
			                                                          Bookmark bookmark = bookmarks.get(position);
			                                                          gotoBookmark(bookmark);
		                                                          }
	                                                          };
	private OnItemLongClickListener bookMarkLongClickLsitener = new OnItemLongClickListener()
	                                                          {
		                                                          @Override
		                                                          public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
			                                                          Bookmark bookmark = bookmarks.get(position);
			                                                          bookMarkDialog.setBookMark(bookmark);
			                                                          bookMarkDialog.setDeleteContent("移除书签");
			                                                          bookMarkDialog.show();
			                                                          return true;
		                                                          }
	                                                          };
	private OnItemClickListener     bookNoteClickListener     = new OnItemClickListener()
	                                                          {
		                                                          
		                                                          @Override
		                                                          public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
			                                                          Bookmark bookmark = bookNotes.get(position);
			                                                          gotoBookmark(bookmark);
		                                                          }
		                                                          
	                                                          };
	
	private OnItemLongClickListener bookNoteLongClickLsitener = new OnItemLongClickListener()
	                                                          {
		                                                          @Override
		                                                          public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
			                                                          Bookmark bookmark = bookNotes.get(position);
			                                                          bookMarkDialog.setBookMark(bookmark);
			                                                          bookMarkDialog.setDeleteContent("移除笔记");
			                                                          bookMarkDialog.show();
			                                                          return true;
		                                                          }
	                                                          };
	
	private void gotoBookmark(Bookmark bookmark) {
		bookmark.markAsAccessed();
		//bmDao.saveBookmark(bookmark);
		myFBReaderApp.runAction(ActionCode.GOTO_BOOKMARK, bookmark.getChapterID(), bookmark.getParagraphIndex(), bookmark.getElementIndex(), bookmark.getCharIndex());
		this.finish();
		
		//UIUtil.showErrorMessage(this, "cannotOpenBook");
	}
	
	/**
	 * @Title AnnotationsActivity.java
	 * @Description 书签adapter
	 * @author zouqp
	 * @Crtdate 2014-10-15
	 */
	class BookMarkAdapter
	        extends
	        BaseAdapter
	{
		
		@Override
		public int getCount() {
			return bookmarks.size();
		}
		
		@Override
		public Object getItem(int position) {
			return bookmarks.get(position);
		}
		
		@Override
		public long getItemId(int position) {
			return position;
		}
		
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			if (convertView == null)
			{
				convertView = LayoutInflater.from(AnnotationsActivity.this).inflate(R.layout.bookmark_item, null);
			}
			TextView textViewDate = (TextView) convertView.findViewById(R.id.bookmark_item_date);
			TextView textViewContent = (TextView) convertView.findViewById(R.id.bookmark_item_content);
			Bookmark bookmark = bookmarks.get(position);
			textViewDate.setText(sdf.format(bookmark.getDate(DateType.Creation)));
			textViewContent.setText(bookmark.getText());
			return convertView;
		}
	}
	
	/**
	 * @Title AnnotationsActivity.java
	 * @Description 笔记的adapter
	 * @author zouqp
	 * @Crtdate 2014-10-15
	 */
	class BookNotesAdapter
	        extends
	        BaseAdapter
	{
		
		@Override
		public int getCount() {
			return bookNotes.size();
		}
		
		@Override
		public Object getItem(int position) {
			return bookNotes.get(position);
		}
		
		@Override
		public long getItemId(int position) {
			return position;
		}
		
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder = null;
			if (convertView == null)
			{
				holder = new ViewHolder();
				convertView = LayoutInflater.from(AnnotationsActivity.this).inflate(R.layout.note_noteinfo_item, null);
				holder.highlightTV = (TextView) convertView.findViewById(R.id.noteinfo_highline);
				holder.noteTV = (TextView) convertView.findViewById(R.id.noteinfo_note);
				holder.timeTV = (TextView) convertView.findViewById(R.id.noteinfo_content_percentTime);
				convertView.setTag(holder);
			}
			else
			{
				holder = (ViewHolder) convertView.getTag();
			}
			
			Bookmark bookmark = (Bookmark) getItem(position);
			holder.highlightTV.setText(context.getResources().getString(R.string.note_item_highlight, bookmark.getText()));
			holder.timeTV.setText(Util.getFormatDate(bookmark.getDate(DateType.Creation).getTime()));
			if (bookmark.getMyTypeID() == 3 && bookmark.getBookNote() != null)
			{
				holder.noteTV.setVisibility(View.VISIBLE);
				holder.noteTV.setText(context.getResources().getString(R.string.note_item_note, bookmark.getBookNote()));
			}
			
			return convertView;
		}
		
		class ViewHolder
		{
			private TextView highlightTV;
			private TextView noteTV;
			private TextView timeTV;
		}
	}
	
	private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
	
	private class ListViewItemClick
	        implements
	        OnItemClickListener
	{
		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
			if (!SDcardUtil.isSDCARDMounted())
			{
				Util.showToast(context, context.getResources().getString(R.string.image_save_sdcard_deny));
				return;
			}
			
			if (bookstatus == 2 && !NetUtil.isNetworkConnected(context))
			{
				new NetworkDialog(context).show();
			}
			else
			{
				openbook(position);
			}
		}
	}
	
	void toReadingBookActivity(String path, int position, String chapterId) {
		myFBReaderApp.runAction(ActionCode.CHANGE_DIRECTORY_BOOKS, path, chapterId);
		if (bookstatus == BookStatus_Enum.ONLINE.getValue())
		{
			if (position + 1 < catalogList.size())
			{
				if (!FileUtil.FileExist(bookId, catalogList.get(position + 1).getId() + ".html")){
//					new QryChapterInfoAction(context, bookId, catalogList.get(position + 1).getId(), null).start();
					new qryChapterInfoUtil().qryChapterInfo(context, bookId, catalogList.get(position + 1).getId());
				}
			}
			if (position - 1 >= 0)
			{
				if (!FileUtil.FileExist(bookId, catalogList.get(position - 1).getId() + ".html")) {
//					new QryChapterInfoAction(context, bookId, catalogList.get(position - 1).getId(), null).start();
					new qryChapterInfoUtil().qryChapterInfo(context, bookId, catalogList.get(position - 1).getId());
				}
			}
		}
		this.finish();
	}
	
	void openbook(int position) {
		if (bookstatus == 3)
		{
			String chapterId = catalogList.get(position).getId();
			//本地书籍
			String path = FileUtil.DownloadPath() + bookId + "/oebps" + catalogList.get(position).getContentSrc();
			System.out.println("localath=====:" + path);
			toReadingBookActivity(path, position, chapterId);
			QyreaderPerferencesUtil.getInstance(context, Const.phone_number).setLocalIndex(bookId, position);
		}
		else
		{
			clickChapterId = catalogList.get(position).getId();
			chapterName = catalogList.get(position).getNavLabel();
			LogUtil.d("bookdectory", "clickChapterId=====:" + clickChapterId);
			String path = FileUtil.OnlinePath(bookId) + clickChapterId + ".html";
			QyreaderPerferencesUtil.getInstance(context, Const.phone_number).setChapterIndex(bookId, position);
			toReadingBookActivity(path, position, clickChapterId);
		}
	}
}
